package com.dailybing.widget;

import java.util.Date;

import com.bingarchive.BingImage;
import com.bingarchive.Network;
import com.bingarchive.Record;
import com.dailybing.R;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.RemoteViews;

public class TodayBing extends AppWidgetProvider implements BingImage.OnLoadListener{

	Context mContext = null;
	AppWidgetManager mAppWidgetManager = null;
	Bitmap mbmSave = null;
	Date mdtSave = null;
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		
		mContext = context;
		mAppWidgetManager = appWidgetManager;
		
		Date _dtNow = new Date();
		
		if(mdtSave != null) {
			if(mdtSave.getDay() == _dtNow.getDay()) {
				return;
			}
		}
		
		BingImage.LoadingImage(mContext, new Record(_dtNow), null, this);
		
//		super.onUpdate(context, appWidgetManager, appWidgetIds);
	}

	@Override
	public void onLoadFinish(Record rcInfo, View vwBox) {
		if(rcInfo.mbmImage == null) {
			if(Network.GetNetworkType(mContext) == Network.NETWORKTYPE_INVALID) {
				return;
			}
			rcInfo.mdtDate = new Date(rcInfo.mdtDate.getTime() - 86400000);
			BingImage.LoadingImage(mContext, rcInfo, null, this);
		} else {
			RemoteViews _rvViews = new RemoteViews(mContext.getPackageName(), R.layout.widget_todaybing);
			_rvViews.setImageViewBitmap(R.id.ivImage, rcInfo.mbmImage);
			_rvViews.setTextViewText(R.id.tvCopyright, rcInfo.mstCopyright);
			
			mdtSave = rcInfo.mdtDate;
			if(mbmSave != null) {
				mbmSave.recycle();
			}
			mbmSave = rcInfo.mbmImage;
			
			mAppWidgetManager.updateAppWidget(new ComponentName(mContext, TodayBing.class), _rvViews);
		}
	}

}
